package com.biyabi.service.impl;

import com.biyabi.dao.BrandMapper;
import com.biyabi.entity.Brand;
import com.biyabi.entity.BrandExample;
import com.biyabi.pojo.BrandsData;
import com.biyabi.service.BrandService;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
@Service
@Transactional
public class BrandServiceImpl implements BrandService {
    @Resource
    private BrandMapper brandMapper;
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public BrandsData findAll(Integer currentPage,Integer pageSize,String columnName,String columnValue){
        currentPage = currentPage == null ? 1:currentPage;
        pageSize= pageSize== null ? 20:pageSize;
        BrandsData brandsData = new BrandsData();
        BrandExample brandExample = new BrandExample();
        if(columnName!=null && columnValue!=null){
            switch (columnName){
                case "name":
                    brandExample.createCriteria().andNameLike("%"+columnValue+"%");
                    break;
                case"introduction":
                    brandExample.createCriteria().andIntroductionLike("%"+columnValue+"%");
                    break;
            }
        }

        brandsData .setTotal(brandMapper.countByExample(brandExample));
        PageHelper.startPage(currentPage,pageSize);
        List<Brand> brands = brandMapper.selectByExample(brandExample);
        brandsData .setRows(brands);
        return brandsData ;
    }
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public List<Brand> findAllBrand(){
        BrandExample brandExample = new BrandExample();
        return brandMapper.selectByExample(brandExample);
    }
    public void add(Brand brand){
        brand.setId(UUID.randomUUID().toString());
        brandMapper.insert(brand);
    }
    public void update(Brand brand){
        brandMapper.updateByPrimaryKey(brand);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public Brand findOne(String id) {
        return brandMapper.selectByPrimaryKey(id);
    }
}
